<template>
  <div class="editor-wrapper">
    <!-- 标题栏 -->
    <header class="header">
      <el-form-item label="文档标题" style="margin-bottom: 0;">
        <el-input v-model="form.title" placeholder="请输入文档标题"></el-input>
      </el-form-item>
    </header>

    <el-form :model="form" label-width="100px" @submit.prevent="submitForm">
      <!-- 动态区块 -->
      <div v-for="(block, index) in form.blocks" :key="index" class="block-item">
        <div class="block-header">
          <span class="block-title">区块 {{ index + 1 }}</span>
          <el-button type="danger" icon="Delete" circle @click="removeBlock(index)" />
        </div>

        <el-form-item label="区块类型">
          <el-select v-model="block.type" placeholder="选择区块类型" @change="handleTypeChange(block)">
            <el-option label="文本" value="text" />
            <el-option label="图片" value="image" />
            <!-- 可继续添加其他类型 -->
          </el-select>
        </el-form-item>

        <!-- 文本区块 -->
        <template v-if="block.type === 'text'">
          <el-form-item label="内容" required>
            <el-input v-model="block.data" type="textarea" :rows="4" placeholder="输入文本内容" />
          </el-form-item>
          <el-form-item label="格式">
            <el-select v-model="block.format" placeholder="选择文本格式">
              <el-option label="Markdown" value="markdown" />
              <el-option label="HTML" value="html" />
            </el-select>
          </el-form-item>
        </template>

        <!-- 图片区块 -->
        <template v-if="block.type === 'image'">
          <el-form-item label="上传图片" required>
            <el-upload action="#" :auto-upload="false" :on-change="(file, fileList) => handleImageChange(file, block)"
              :show-file-list="false">
              <img v-if="block.preview" :src="block.preview" class="image-preview" />
              <el-icon v-else class="image-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="宽度">
                <el-input-number v-model="block.width" :min="1" controls-position="right" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="高度">
                <el-input-number v-model="block.height" :min="1" controls-position="right" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <el-divider />
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="addBlock('text')">➕ 添加文本块</el-button>
        <el-button type="success" @click="addBlock('image')">📷 添加图片块</el-button>
        <el-button type="primary" native-type="submit" :loading="loading" :disabled="loading">
          {{ loading ? '提交中...' : '✅ 提交内容' }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { postsAPI } from '../../api/posts';
import { uploadAPI } from '../../api/upload';
import { ref } from 'vue';

const loading = ref(false);

const form = reactive({
  title: '', // 新增标题字段
  blocks: [],
  version: '1.0'
});

// 初始化新区块
const createBlock = (type) => {
  const base = { type };
  switch (type) {
    case 'text':
      return { ...base, data: '', format: 'markdown' };
    case 'image':
      return {
        ...base,
        url: null,      // 最终服务器URL
        preview: null,  // 本地预览URL
        file: null,     // 原始文件对象
        width: null,
        height: null
      };
    default:
      return base;
  }
};

// 添加区块
const addBlock = (type) => {
  form.blocks.push(createBlock(type));
};

// 删除区块
const removeBlock = (index) => {
  form.blocks.splice(index, 1);
};

// 类型变化时重置数据
const handleTypeChange = (block) => {
  const newBlock = createBlock(block.type);
  Object.assign(block, newBlock);
};

// 图片处理
const handleImageChange = (file, block) => {
  if (!file.raw) return;

  // 清除旧文件引用
  URL.revokeObjectURL(block.preview);

  // 创建本地预览
  block.preview = URL.createObjectURL(file.raw);
  block.file = file.raw;  // 保存文件对象用于后续上传

  // 获取图片尺寸
  const img = new Image();
  img.src = block.preview;
  img.onload = () => {
    block.width = img.naturalWidth;
    block.height = img.naturalHeight;
  };
};
const resetForm = () => {
  form.title = '';
  form.blocks = [];
};
// 提交表单
const submitForm = async () => {
  try {
    loading.value = true;
    // 简单验证
    if (!form.title.trim()) {
      ElMessage.error('文档标题不能为空');
      return;
    }

    for (const [index, block] of form.blocks.entries()) {
      if (block.type === 'text' && !block.data.trim()) {
        ElMessage.error(`第 ${index + 1} 个文本块内容不能为空`);
        return;
      }
      if (block.type === 'image' && !block.file && !block.url) {
        ElMessage.error(`第 ${index + 1} 个图片块必须上传图片`);
        return;
      }
    }

    const needUploadBlocks = form.blocks.filter(
      block => block.type === 'image' && block.file
    );

    // 批量上传图片
    if (needUploadBlocks.length > 0) {
      ElMessage.info(`上传${needUploadBlocks.length}张图片...`);
      
      // 使用Promise.allSettled获取详细错误
      const uploadResults = await Promise.allSettled(
        needUploadBlocks.map((block, index) =>
          uploadAPI.uploadPost(block.file)
            .then(res => {
              if (!res.url) throw new Error('未收到文件URL');
              return { block, url: res.url };
            })
            .catch(error => {
              console.error(`第${index + 1}个文件上传失败:`, error.response?.data || error.message);
              throw new Error(`图片${index + 1}上传失败: ${error.message}`);
            })
        )
      );

      // 检查所有结果
      const failedUploads = uploadResults.filter(r => r.status === 'rejected');
      if (failedUploads.length > 0) {
        failedUploads.forEach((r, i) => {
          console.error(`失败${i + 1}:`, r.reason);
          ElMessage.error(r.reason.message);
        });
        throw new Error(`${failedUploads.length}张图片上传失败`);
      }

      // 更新URL
      uploadResults.forEach(result => {
        if (result.status === 'fulfilled') {
          const { block, url } = result.value;
          block.url = url;
          block.preview = null;
          block.file = null;
        }
      });
    }

    // 构造最终数据
    const result = {
      title: form.title,
      content: {
        blocks: form.blocks.map(block => {
          const base = { type: block.type };
          switch (block.type) {
            case 'text':
              return { ...base, data: block.data, format: block.format };
            case 'image':
              return {
                ...base,
                url: block.url,
                width: block.width,
                height: block.height
              };
            default:
              return base;
          }
        }),
        version: form.version
      }
    };

    // 提交到后端
    await postsAPI.createPost(result);
    ElMessage.success('提交成功！');
    resetForm();
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error(`提交失败: ${error.message || '请检查网络连接后重试'}`);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.editor-wrapper {
  max-width: 900px;
  margin: 30px auto;
  padding: 20px;
  background-color: #f9fafb;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.header .el-input {
  width: 80%;
  margin: 0 auto;
}

.block-item {
  position: relative;
  background-color: #ffffff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 25px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.block-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.block-title {
  font-weight: bold;
  color: #333;
}

.el-form-item__label {
  font-weight: 500;
  color: #5a5e66;
}

.image-preview {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.el-select,
.el-input-number {
  width: 100%;
}

.el-divider {
  margin: 15px 0;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  justify-content: center;
}

.ml-2 {
  margin-left: 8px;
}

@media (max-width: 768px) {
  .block-item {
    padding: 15px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
}
</style>